/***********************************************************************

 Copyright (c) 2009, Luke Malcolm, www.lukemalcolm.com

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 ***********************************************************************/

#include "ofxSMSsqlite.h"
#include <fstream>
#include <iostream>


ofxSMSsqlite::ofxSMSsqlite()
{

}

ofxSMSsqlite::~ofxSMSsqlite()
{

}

void ofxSMSsqlite::setAutoSave(string filename, ofxSMS * smsObject, float seconds){

	autoSaveTimer.setup(seconds, true);

    autoSaveSMSObject   = smsObject;
    autoSaveFilename    = filename;

	//events
	ofAddListener(autoSaveTimer.TIMER_REACHED, this, &ofxSMSsqlite::autoSave);

};

bool ofxSMSsqlite::exportToFile(string dbFilename, string exportFilename){

    if(DBExists(dbFilename)){

        sqlite = new ofxSQLite(dbFilename);

        processSQLError(sqlite->getError(),"ofxSMSsqlite::export - Load DB Error: %s\n");

        ofxSQLiteSelect sel = sqlite->select("uuid, message, fromN, read, datetimeBlob").from("messages");

        processSQLError(sqlite->getError(),"ofxSMSsqlite::export - Select Query Error: %s\n");

        sel.execute().begin();

        processSQLError(sqlite->getError(),"ofxSMSsqlite::load - Select Query Execute Error: %s\n");

        ofstream exportFile;
        exportFile.open (exportFilename.c_str());

        cout        << "id|text|from|read|raw_datetime|datetime\n";
        exportFile  << "id|text|from|read|raw_datetime|datetime\n";

        while(sel.hasNext()) {

            ofxSMSMessage tmpMsg;

            tmpMsg.id = sel.getString();
            tmpMsg.text = sel.getString();
            tmpMsg.from = sel.getString();
            tmpMsg.bRead = sel.getInt();
            tmpMsg.datetime = sel.getInt();

            cout        << tmpMsg.id << "|" << tmpMsg.text << "|" << tmpMsg.from << "|" << tmpMsg.bRead << "|" << tmpMsg.datetime << "|" << ctime(&tmpMsg.datetime); // << endl;  Not required because ctime as an EOL
            exportFile  << tmpMsg.id << "|" << tmpMsg.text << "|" << tmpMsg.from << "|" << tmpMsg.bRead << "|" << tmpMsg.datetime << "|" << ctime(&tmpMsg.datetime); // << endl;  Not required because ctime as an EOL

            sel.next();
        }

        exportFile.close();
        delete sqlite;
        return true;

    }
    else {
        ofLog(OF_LOG_ERROR,"ofxSMSsqlite::export - DB File does not exist: %s\n", dbFilename.c_str());
        return false;
    }
}

bool ofxSMSsqlite::load(string filename, ofxSMS * smsObjectPtr){

    if(DBExists(filename)){

        sqlite = new ofxSQLite(filename);

        processSQLError(sqlite->getError(),"ofxSMSsqlite::load - Load DB Error: %s\n");

        ofxSQLiteSelect sel = sqlite->select("uuid, message, fromN, read, datetimeBlob").from("messages");

        processSQLError(sqlite->getError(),"ofxSMSsqlite::load - Select Query Error: %s\n");

        sel.execute().begin();

        processSQLError(sqlite->getError(),"ofxSMSsqlite::load - Select Query Execute Error: %s\n");

        while(sel.hasNext()) {

            ofxSMSMessage tmpMsg;

            tmpMsg.id = sel.getString();
            tmpMsg.text = sel.getString();
            tmpMsg.from = sel.getString();
            tmpMsg.bRead = sel.getInt();
            tmpMsg.datetime = sel.getInt();
            //cout << uuid << ", " << message << ", " << fromN << ", " << read << ctime(&datetime) << endl;
            (*smsObjectPtr).all.push_back(tmpMsg);

            if (tmpMsg.bRead) {
               (*smsObjectPtr).read.push_back(tmpMsg);
            }
            else {
               (*smsObjectPtr).unread.push_back(tmpMsg);
            }

            ofLog(OF_LOG_VERBOSE,"ofxSMSsqlite::load - Loaded SMS UUID %s\n",tmpMsg.id.c_str());
            sel.next();
        }

        delete sqlite;

    }
    else {
        ofLog(OF_LOG_ERROR,"ofxSMSsqlite::load - DB File does not exist: %s\n", filename.c_str());
    }

}


void ofxSMSsqlite::autoSave(ofEventArgs &e){
    save(autoSaveFilename, autoSaveSMSObject);
}

bool ofxSMSsqlite::save(string filename, ofxSMS * smsObject){

    //Due to the long delay during writing to SQLite DB, we run the save function as a threaded activity.

    if (!saveThread.isThreadRunning()) {
        saveThread.start();
    }

    saveThread.smsObject = smsObject;
    saveThread.filename  = filename;
    saveThread.doSave    = true;





}


